//
//  FFWorld.m
//  ForceField
//
//  Created by Roxanne Brittain on 11/23/11.
//  Copyright (c) 2011 Digifit. All rights reserved.
//

#import "FFWorld.h"

FFObjectWrapper* FFWorld::addNewObject()
{
    FFObject *object = new FFObject();
    m_objectVector.push_back(object);
    object->idNumber = nextIDNumber++;
    
    FFObjectWrapper *wrapper = [FFObjectWrapper objectWithCPPObject:object];
    return wrapper;
}

void FFWorld::refreshWithSeconds(float s)
{
    if (!playing) return;
    
    std::vector<FFObject*>::iterator it;
    
    for (it=m_objectVector.begin(); it < m_objectVector.end(); it++ )
    {
        FFObject *object = *it;
        object->clearForces();
        
        //turn gravity in to a force and apply it
        FFVector *acc = this->getGravity();
        FFVector *force = new FFVector(acc->getX()*object->getMass(),acc->getY()*object->getMass());
        object->applyForce(force);
    }
    
    //apply other forces
    if (m_objectVector.size()>1) {
        fieldHandler->applyForceFields(m_objectVector);
        collisionHandler->checkCollisions(m_objectVector);
    }
    
    for (it=m_objectVector.begin(); it < m_objectVector.end(); it++ )
    {
        FFObject *object = *it;
        
        if (!object->dragging) {
            //update objects acceleration
            object->updateAcceleration();
            
            //have the object update it's velocity
            object->updateVelocityWithSeconds(s);
            
            //check if hit walls
            object->checkBoundaries(worldBounds.origin.x, worldBounds.origin.y, worldBounds.size.width, worldBounds.size.height);
            
            //have the object update it's position
            object->updatePositionWithSeconds(s);
            
            //check for collisions
            
        }
        
        //tell observer update it ready
        [object->observer objectDidUpdate];
    }
}